package cn.zhxu.crud.service;

import lombok.Getter;
import lombok.Setter;

import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;

public class Saved<T> {

    public final T old;     // 可空
    public final T now;     // 非空

    public Saved(T old, T now) {
        this.old = old;
        this.now = now;
    }

    @Setter
    @Getter
    private Object attach;  // 额外数据

    public <R> R getOld(Function<T, R> getter) {
        if (old == null) {
            return null;
        }
        return getter.apply(old);
    }

    public <R> R getNow(Function<T, R> getter) {
        if (now == null) {
            return null;
        }
        return getter.apply(now);
    }

    public <R> boolean isDirty(Function<T, R> getter) {
        var oldValue = getOld(getter);
        var nowValue = getNow(getter);
        return !Objects.equals(oldValue, nowValue);
    }

    public <R> R getDirtyOld(Function<T, R> getter) {
        var oldValue = getOld(getter);
        var nowValue = getNow(getter);
        if (Objects.equals(oldValue, nowValue)) {
            return null;
        }
        return oldValue;
    }

    public <R> void onDirtyOld(Function<T, R> getter, Consumer<R> consumer) {
        var oldValue = getDirtyOld(getter);
        if (oldValue != null) {
            consumer.accept(oldValue);
        }
    }

    public boolean isCreating() {
        return old == null;
    }

}
